package com.kyzh.core.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.impls.GameImpl
import com.gushenge.core.toast
import com.kyzh.core.R
import com.kyzh.core.activities.BackgroundActivity
import com.kyzh.core.activities.GameBackGroundActivity
import com.kyzh.core.adapters.BackgroundAdapter
import com.kyzh.core.extension.intentExtras
import kotlinx.android.synthetic.main.fragment_background.*

class BackgroundFragment : BaseFragment() {

    private val mAdapter by lazy { BackgroundAdapter() }

    private val mType by intentExtras("position", 1)

    companion object {
        fun getInstance(position: Int): BackgroundFragment {
            val fragment = BackgroundFragment()
            val bundle = Bundle()
            bundle.putInt("position", position)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_background, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    private fun initView() {
        recyclerView.adapter = mAdapter
        mAdapter.addChildClickViewIds(R.id.tvDel, R.id.tvEnterBackground)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.tvDel -> delGame(position)
                R.id.tvEnterBackground -> enterBackGround(position)
            }
        }
        refresh.setEnableLoadMore(false)
        refresh.setOnRefreshListener {
            getData()
        }

    }

    private fun initData() {
        getData()
    }

    // 删除游戏
    private fun delGame(position: Int) {
        GameImpl.delGame(mAdapter.data[position].id) {
            if (this.code == 1) {
                refresh.autoRefresh()
                val activity = activity as BackgroundActivity
                activity.refreshNumber()
            }
            this.msg.toast()
        }
    }

    // 进入后台
    private fun enterBackGround(position: Int) {
        GameBackGroundActivity.start(requireContext(), mAdapter.data[position].id)
    }

    private fun getData() {
        GameImpl.getBindGameList(mType) {
            if (this.size > 0) {
                recyclerView.visibility = View.VISIBLE
                notData.visibility = View.GONE
                mAdapter.setNewInstance(this)
            } else {
                recyclerView.visibility = View.GONE
                notData.visibility = View.VISIBLE
            }
            refresh.finishRefresh()
        }
    }

}
